<template>
  <view class="content">
    <view class="input-group">
      <view class="input-row border">
        <text class="title">账号：</text>
        <m-input class="m-input" type="text" clearable focus v-model="username" placeholder="请输入账号"></m-input>
      </view>
      <view class="input-row border">
        <text class="title">密码：</text>
        <m-input type="password" displayable v-model="password" placeholder="请输入密码"></m-input>
      </view>
      <view v-if="needCaptcha" class="input-row">
        <text class="title">验证码：</text>
        <m-input type="text" v-model="captchaText" placeholder="请输入验证码"></m-input>
        <view class="send-code-btn captcha-view" @click="captcha('refreshCaptcha')">
          <i v-if="captchaing" class="uni-icon_toast uni-loading"></i>
          <img v-if="!captchaing" :src="captchaBase64" width="100%" height="100%" />
        </view>
      </view>
    </view>
    <view class="btn-row">
      <button type="primary" class="primary" :loading="loginBtnLoading" @tap="bindLogin">登录</button>
    </view>
    <view class="action-row">
      <navigator url="../reg/reg">注册账号</navigator>
    </view>
  </view>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import mInput from '../../components/m-input.vue'
import { univerifyLogin, univerifyErrorHandler } from '@/common/univerify.js'
import { getDeviceUUID } from '@/common/utils.js'
import { apiLogin } from '@/api/userInfo.js'

let weixinAuthService
const captchaOptions = {
  deviceId: getDeviceUUID(),
  scene: 'login'
}

export default {
  components: {
    mInput
  },
  data() {
    return {
      platform: uni.getSystemInfoSync().platform,
      mobile: '',
      code: '',
      username: '',
      password: '',
      positionTop: 0,
      isDevtools: false,
      codeDuration: 0,
      loginBtnLoading: false,
      hasAppleLogin: false,
      needCaptcha: uni.getStorageSync('uni-needCaptcha'),
      captchaing: false,
      captchaBase64: '',
      captchaText: ''
    }
  },
  computed: mapState(['forcedLogin', 'hasLogin', 'univerifyErrorMsg', 'hideUniverify']),
  onLoad() {
    if (this.needCaptcha) {
      this.captcha('createCaptcha')
    }
  },
  methods: {
    ...mapMutations(['login']),
    initPosition() {
      /**
       * 使用 absolute 定位，并且设置 bottom 值进行定位。软键盘弹出时，底部会因为窗口变化而被顶上来。
       * 反向使用 top 进行定位，可以避免此问题。
       */
      this.positionTop = uni.getSystemInfoSync().windowHeight - 100
    },
    async loginByPwd() {
      /**
       * 客户端对账号信息进行一些必要的校验。
       * 实际开发中，根据业务需要进行处理，这里仅做示例。
       */
      if (this.username.length < 3) {
        uni.showToast({
          icon: 'none',
          title: '账号最短为 3 个字符'
        })
        return
      }
      if (this.password.length < 6) {
        uni.showToast({
          icon: 'none',
          title: '密码最短为 6 个字符'
        })
        return
      }
      const paramObject = {
        account: this.username,
        password: this.password
        // captcha: this.captchaText,
        // ...captchaOptions
      }
      this.loginBtnLoading = true

      apiLogin(paramObject)
        .then(res => {
          this.loginBtnLoading = false
          this.needCaptcha = false
          res.userInfo.id = undefined
          uni.setStorageSync('accountInfo', paramObject)
          uni.setStorageSync('uni_id_token', res.token)
          uni.setStorageSync('username', res.userInfo.userName)
          uni.setStorageSync('userInfo', res.userInfo)
          uni.setStorageSync('login_type', 'online')
          uni.setStorageSync('uni_id_has_pwd', true)
          this.toMain(res.userInfo.userName)
        })
        .catch(err => {
          this.loginBtnLoading = false
          uni.showModal({
            content: err,
            showCancel: false
          })
        })
    },
    bindLogin() {
      this.loginByPwd()
    },
    toMain(userName) {
      this.login(userName)
      /**
       * 强制登录时使用reLaunch方式跳转过来
       * 返回首页也使用reLaunch方式
       */
      uni.reLaunch({
        url: '../main/main'
      })
    },
    async captcha(action, args) {
      if (this.captchaing) return

      // 验证不loading
      this.captchaing = true

      let { result: res } = await uniCloud.callFunction({
        name: 'user-center',
        data: {
          action,
          params: {
            ...captchaOptions,
            ...args
          }
        }
      })
      this.captchaing = false
      if (res.code === 0) {
        this.captchaBase64 = res.captchaBase64
      } else {
        uni.showToast({
          icon: 'none',
          title: res.message,
          duration: 1000
        })
      }
      return res
    }
  },
  onReady() {
    this.initPosition()
    // #ifdef MP-WEIXIN
    this.isDevtools = uni.getSystemInfoSync().platform === 'devtools'
    // #endif
  }
}
</script>

<style>
.login-type {
  display: flex;
  justify-content: center;
}

.login-type-btn {
  line-height: 30px;
  margin: 0px 15px;
}

.login-type-btn.act {
  color: #0faeff;
  border-bottom: solid 1px #0faeff;
}

.send-code-btn {
  width: 120px;
  text-align: center;
  background-color: #0faeff;
  color: #ffffff;
}

.action-row {
  display: flex;
  flex-direction: row;
  justify-content: center;
}

.action-row navigator {
  color: #007aff;
  padding: 0 10px;
}

.oauth-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
  flex-wrap: wrap;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
}

.oauth-image {
  position: relative;
  width: 50px;
  height: 50px;
  border: 1px solid #dddddd;
  border-radius: 50px;
  background-color: #ffffff;
}

.oauth-image image {
  width: 30px;
  height: 30px;
  margin: 10px;
}

.oauth-image button {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
}

.captcha-view {
  line-height: 0;
  justify-content: center;
  align-items: center;
  display: flex;
  position: relative;
  background-color: #f3f3f3;
}
</style>
